import pdb
import os
from pyaspell import Aspell
spell = Aspell([('master','./data/private'),('lang','en')])
location = '/home/radian/workspace/Python/Qur2an Renamer/qren-console/test/fixture/testcase1/'
LEN_QURAN = 114

def folder_analyize(location):
    group = {
        'files' : [],
        'sub-groups' : [],
        'path' : location
    }

    for filename in os.listdir(location):
        fullname = os.path.join(location, filename)
        if not os.path.isfile(fullname):
            group['sub-groups'].append(folder_analyize(fullname))
            continue

        # actual data here pls
	basename, extension = os.path.splitext(filename)
        group['files'].append({
            'filename' : basename,
            'extension' : extension,
            'fullpath' : os.path.join(location, filename) ,
            'suggested_names' : spell.suggest(basename)
        })

    len_files = len(group['files'])
    group['need_regrouping'] = len_files > LEN_QURAN
    group['incomplete'] = len_files < LEN_QURAN
    return group
    
def common_substring_analyize(groups):
    for group in groups:
        group['common_substring'] = long_substr([f['filename'] for f in group['files']])

def long_substr(data):
    substr = ''
    if len(data) > 1 and len(data[0]) > 0:
        for i in range(len(data[0])):
            for j in range(len(data[0])-i+1):
                if j > len(substr) and _is_substr(data[0][i:i+j], data):
                    substr = data[0][i:i+j]
    return substr

def _is_substr(find, data):
    if len(data) < 1 and len(find) < 1:
        return False
    for i in range(len(data)):
        if find not in data[i]:
            return False
    return True



'''
        for subdirname in dirnames:
            print os.path.join(dirname, subdirname)



for dirname, dirnames, filenames in os.walk(location):
    for subdirname in dirnames:
        print os.path.join(dirname, subdirname)

    qFiles = []
    for filename in filenames:
        qFiles.append({
            'filename' : filename,
            'extension' : filename,
            'fullpath' : filename,
            'suggested_names' : []
        })
    len_files = len(qFiles)
    qFiles = {
        'files' : qFiles,
        'need_regrouping' : len_files > LEN_QURAN,
        'incomplete' : len_files < LEN_QURAN
    }
    if qFi

        #print os.path.join(dirname, filename)





print long_substr(['Oh, hello, my friend.',
                   'I prefer Jelly Belly beans.',
                   'When hell freezes over!'])
'''

def execute(data, extensions=['.mp3']):
    for fdata in data['files']:
        if fdata['extension'] not in extensions:
            continue
        os.renames(fdata['fullpath'], os.path.join(data['path'], fdata['suggested_names'][0])+fdata['extension'])

    for sub_data in data['sub-groups']:
        execute(sub_data, extensions)
